package borge.web.teamspirit.client.page.team.widgets;

import java.util.HashMap;
import java.util.List;

import borge.web.teamspirit.client.SessionData;
import borge.web.teamspirit.client.TeamSpirit;
import borge.web.teamspirit.client.data.Comment;
import borge.web.teamspirit.client.data.Match;
import borge.web.teamspirit.client.data.MatchAttendance;
import borge.web.teamspirit.client.data.MatchPlayerStats;
import borge.web.teamspirit.client.data.TeamPlayer;
import borge.web.teamspirit.client.data.TeamSerieInfo;
import borge.web.teamspirit.client.interfaces.PersistentData;
import borge.web.teamspirit.client.interfaces.ServerCallbackHandler;
import borge.web.teamspirit.client.interfaces.WidgetEventHandler;
import borge.web.teamspirit.client.interfaces.PersistentData.DataKey;
import borge.web.teamspirit.client.page.shared.widgets.ShowCommentsWidget;
import borge.web.teamspirit.client.servercomm.DBQuery;
import borge.web.teamspirit.client.servercomm.DBQueryResults;
import borge.web.teamspirit.client.servercomm.ServerComm;
import borge.web.teamspirit.client.servercomm.DBQueryResults.Result;

import com.google.gwt.event.logical.shared.BeforeSelectionEvent;
import com.google.gwt.event.logical.shared.BeforeSelectionHandler;
import com.google.gwt.user.client.ui.FlexTable;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.VerticalPanel;

public class ShowMatchWidget extends ShowTabbedDataWidget implements BeforeSelectionHandler<Integer> {

	private Match iMatch;
	private String iNewMatchKey;
	private Label iSerieLabel;

	private ServerCallbackHandler iServerHandler;
	
    private static final int GENERAL_INDEX = 0;
    private static final int ATTENDANCE_INDEX = 1;
    private static final int STATISTICS_INDEX = 2;
    private static final int DISCUSSION_INDEX = 3;
    
    private HashMap<String, MatchAttendance> iAttendanceMap;
    
    private ShowCommentsWidget iShowComments;
	
    private static final String[] iTabTitles = {
            TeamSpirit.getConstants().general(),
            TeamSpirit.getConstants().attendance(),
            TeamSpirit.getConstants().statistics(),
            TeamSpirit.getConstants().discussion()};

	
	public ShowMatchWidget(WidgetEventHandler aEventHandler, ServerCallbackHandler aHandler) {
		super(aEventHandler, iTabTitles);
		
		iServerHandler = aHandler;
		iSerieLabel = new Label();

		iPanel.addBeforeSelectionHandler(this);
        iPanel.selectTab(0);
        initWidget(iPanel);
	}

	
	public void fillPanels(){
		
		if(SessionData.sCurrentTeam != null){
			TeamSerieInfo tsi = SessionData.sCurrentTeam.getSerieInfoByKey(iMatch.getOwningSerieKey());
			iSerieLabel.setText("Match in serie: " + tsi.getLeagueSeason() + ":" + tsi.getLeagueDivision());
		}
		
		fillGeneral();
		fillAttendance();
		fillStatistics();
		fillDiscussion();
	}
	
	public void fillGeneral(){
	
		int row = 0, column = 0;
		
		iTabPanels.get(GENERAL_INDEX).add(iSerieLabel);
		
		FlexTable table = iTabTables.get(GENERAL_INDEX);
		
		table.setText(row, column++, iConstants.opponents());
		table.setText(row++, column--, iMatch.getOpponents());
		
	}
	
	public void fillAttendance(){
		
		List<PersistentData> attendance = iMatch.getAttendance();
		
		if(attendance == null || SessionData.getTeamPlayers() == null)
			return;
		
		if(iAttendanceMap == null)
			iAttendanceMap = new HashMap<String, MatchAttendance>();
		iAttendanceMap.clear();
		
		for(PersistentData pd : attendance){
			MatchAttendance ma = (MatchAttendance)pd;
			iAttendanceMap.put(ma.getPlayerKey(), ma);
		}
		
		List<PersistentData> players = SessionData.getTeamPlayers();
		FlexTable table = iTabTables.get(ATTENDANCE_INDEX);
		int row = 0, column = 0;
		
		for(PersistentData pd : players){
			TeamPlayer player = (TeamPlayer)pd;
			
			MatchAttendance ma = iAttendanceMap.get(player.getEncodedKey());
			String answer = MatchAttendance.UNANSWERED;
			if(ma != null)
				answer = ma.getAttendValue();
			
			table.setText(row, column++, player.getPersonName());
			table.setText(row++, column--, answer);
		}
		
		
	}
	
	public void fillStatistics(){
		
		List<PersistentData> stats = iMatch.getPlayerStats();
		
		if(stats == null)
			return;
		
		FlexTable table = iTabTables.get(STATISTICS_INDEX);
		
		int row = 0, column = 0;
		for(PersistentData pd : stats){
			
			MatchPlayerStats mps = (MatchPlayerStats)pd;
			TeamPlayer player = SessionData.sCurrentTeam.getPlayerByKey(mps.getPlayerKey());
			String name = "Unknown";
			if(player != null)
				name = player.toString();
			table.setText(row++, column, name);
			table.setText(row++, column, Integer.toString(mps.getGoals()));
			table.setText(row++, column, Integer.toString(mps.getAssists()));
			table.setText(row++, column, Boolean.toString(mps.getYellowCard()));
			table.setText(row++, column, Boolean.toString(mps.getRedCard()));
			table.setText(row++, column, "---");
			
		}
		
	}
	
	public void fillDiscussion(){
		
		if(iMatch.getComments() == null)
    		return;
    	
    	if(iShowComments == null){
    		iShowComments = new ShowCommentsWidget(null);
    		iTabPanels.get(DISCUSSION_INDEX).add(iShowComments);	
    	}
    	
    	iShowComments.setAndDisplay(iMatch.getComments());
		
	}
	
	@Override
	public boolean needsUpdate(String aData) {
		
		
		// check if we can get cached match from current/cached series
		// if not, request match from db
		
		Match match = null;
		if(SessionData.sCurrentSerie != null && 
				(match = SessionData.sCurrentSerie.getMatchByKey(aData)) != null){
			// we already have the serie

			if(iMatch == null || !match.getEncodedKey().equals(iMatch.getEncodedKey())){
				iMatch = match;
				fillPanels();
			}

			return false;
		}
		
		iNewMatchKey = aData;
		
		return true;
	}

	@Override
	public void populateData(DBQueryResults results) {
		
		// TODO: add error handling
		// TODO: only update relevant panel
		Result result = results.getResult(DataKey.MATCH);
		if(result != null){
			iMatch = (Match)result.getResultList().get(0);
			fillGeneral();
		}
		
		result = results.getResult(DataKey.ATTENDANCE);
		if(result != null){
			iMatch.setAttendance(result.getResultList());
			fillAttendance();
		}
		
		result = results.getResult(DataKey.MATCHSTATS);
		
		if(result != null){
			iMatch.setPlayerStats(result.getResultList());
			fillStatistics();
		}
		
		result = results.getResult(DataKey.COMMENT);
		
		if(result != null){
			iMatch.setComments(result.getResultList());
			fillDiscussion();
		}
		
		//fillPanels();

		
	}

	@Override
	public void requestServerData(ServerCallbackHandler aHandler) {

		iServerHandler = aHandler;
		DBQuery query = new DBQuery(DataKey.MATCH, Match.class.getName());
		query.addFilter("iEncodedKey", DBQuery.EQUALS, "matchParam", "String", iNewMatchKey, null);
		ServerComm.getObjectList(query, aHandler);
		
	}


	@Override
	public void onBeforeSelection(BeforeSelectionEvent<Integer> event) {
		// TODO Auto-generated method stub
	
		int index = event.getItem();
		
		if(index == STATISTICS_INDEX && iMatch.getPlayerStats() == null){
			// must fetch from db
			DBQuery query = new DBQuery(DataKey.MATCHSTATS, MatchPlayerStats.class.getName());
			query.addFilter("iMatchKey", DBQuery.EQUALS, "matchKey", "String", iMatch.getEncodedKey(), null);
			ServerComm.getObjectList(query, iServerHandler);
		}
		else if(index == ATTENDANCE_INDEX && iMatch.getAttendance() == null){
			DBQuery query = new DBQuery(DataKey.ATTENDANCE, MatchAttendance.class.getName());
			query.addFilter("iMatchKey", DBQuery.EQUALS, "matchKey", "String", iMatch.getEncodedKey(), null);
			ServerComm.getObjectList(query, iServerHandler);
		}
		else if(index == DISCUSSION_INDEX && iMatch.getComments() == null){
			DBQuery query = new DBQuery(DataKey.COMMENT, Comment.class.getName());
			query.addFilter("iParentKey", DBQuery.EQUALS, "matchKey", "String", iMatch.getEncodedKey(), null);
			ServerComm.getObjectList(query, iServerHandler);
		}
		
	}

}
